//
//  NewsDetailController.m
//  ios_news
//
//  Created by Han on 14-6-15.
//  Copyright (c) 2014年 ucoder. All rights reserved.
//

#import "NewsDetailController.h"
#import "Util.h"




@implementation NewsDetailController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil nid:(NSInteger)nid
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    //NSLog(@"%ld", (long)nid);
    mNid = nid;
    if (self) {
    
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.navigationBarHidden = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = MAIN_COLOR;
    self.navigationController.navigationBar.translucent = NO;  // 半透明
    
    [self addButton];
    
    
    mMenu = [[SettingMenu alloc]initWithFrame:CGRectMake(0, -150, 320, 150) RootViewController:self];
    
    mLoadingView = [LoadingView add:self.view initWithFrame:CGRectMake(0, 0, 320, GLOBLE_HEIGHT - 64) viewTag:0];
    
    mReloadView = [[ReloadView alloc] initWithFrame:CGRectMake(0, 0, 320, GLOBLE_HEIGHT - 64) RootViewController:self];
    [self.view addSubview:mReloadView];
    mReloadView.hidden = YES;
    
    
    
    mWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, GLOBLE_HEIGHT - 64)];
    mWebView.delegate = self;
    mWebView.hidden = YES;
    [self.view addSubview: mWebView];
    
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self getIsFav]) {
        mFavButton.selected = YES;
    }
    
    [MobClick beginLogPageView:@"NewsDetailController"];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [MobClick endLogPageView:@"NewsDetailController"];
}


- (void) loadData
{
    mLoadingView.hidden = NO;
    mReloadView.hidden = YES;
    
    //NSLog(@"loadData++++++++++");
    
    NSString *url = [[NSString alloc] initWithFormat:API_NEWS_DETAIL, (long)mNid];
    
    NSURLSessionTask *task = [NewsDetail getDataWithBlock:^(NewsDetail *data, NSError *error) {
        
        mLoadingView.hidden = YES;
        
        if (!error) {
            mData = data;
            mWebView.hidden = NO;
            
            [self webViewLoadHTMLString];
            
        } else {
            //NSLog(@"%@", error);
            mReloadView.hidden = NO;
        }
    } :url];
}

- (void) webViewLoadHTMLString
{
    
    NSString *cssPath = @"style.css";
    NSString *titleStyle = [NSString stringWithFormat:@"<span style='font-size:%dpx'>", 17 + 4];
    NSString *titleColor = @"#333333";

    //去掉所有的image的格式
    mData.body = [mData.body stringByReplacingOccurrencesOfString:@"style=\".*?\"" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, mData.body.length)];
    
    
    if (mData.newsRelated.count != 0) {
        NSString *html = [[NSString alloc] init];
        
        html = [html stringByAppendingString:@"<tap>相关新闻</tap><br /><HR style='FILTER: progid:DXImageTransform.Microsoft.Shadow(color:#987cb9,direction:145,strength:15)' width='100%' color=#CCCCCC SIZE=1>"];
        for (int i = 0; i < mData.newsRelated.count; i++) {
            NSString *path = [NSString stringWithFormat:@"http://wallstreetcn.com/node/%@",[[mData.newsRelated objectAtIndex:i] objectForKey:@"target_id"]];
            NSString *title = [[mData.newsRelated objectAtIndex:i] objectForKey:@"title"];
            html = [html stringByAppendingString:[NSString stringWithFormat:@"<li><a href=\"%@\">%@</a></li><HR style=\"FILTER: progid:DXImageTransform.Microsoft.Shadow(color:#987cb9,direction:145,strength:15)\" color=#CCCCCC SIZE=1>",path,title]];
        }
        
        mData.body = [mData.body stringByAppendingString:html];
    }
    
    
    NSString *html = [NSString stringWithFormat:@"<html><link href=\"%@\" rel=\"stylesheet\" type=\"text/css\"/><head><title></title><div style='line-height:10px'><img class='img_title' src='htmltitle@2x.png'/></div><strong>%@%@</strong><div style='line-height:10px'><font size=2.0; color='%@'><br/>文/%@ %@</font></div></head><body style='color:%@;'><div id=\"wscn-app\">%@</div></body></html>",cssPath, titleStyle, mData.title, titleColor, mData.name, mData.date, titleColor, mData.body];

    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    //NSLog(@"%@", baseURL);

    
    
    [mWebView loadHTMLString: html baseURL:baseURL];
}

- (void)fontChanged:(NSString *) sizeofFont
{
    NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%@;", sizeofFont];
    [mWebView stringByEvaluatingJavaScriptFromString:jsString];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *requestURL = [request URL];
    NSString *path = [requestURL path];
    
    
    if ([[requestURL scheme] isEqualToString:@"http"] && (navigationType == UIWebViewNavigationTypeLinkClicked))
    {
        NSInteger nid = [[[path componentsSeparatedByString:@"/"] objectAtIndex:2] intValue];
        
        //NSLog(@"%d", nid);
        
        NewsDetailController *newsDetailCtr = [[NewsDetailController alloc] initWithNibName:nil bundle:nil nid: nid];
        newsDetailCtr.hidesBottomBarWhenPushed = YES; // 详情页隐藏tabbar
        
        [self.navigationController pushViewController:newsDetailCtr animated:YES];
        
        return NO;
    }
    
    return YES;
}



//添加按钮
-(void)addButton
{
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.exclusiveTouch = YES;
    leftButton.frame = CGRectMake(0, 0, 44, 44);
    //button.backgroundColor = [UIColor redColor];
    
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    leftButton.imageEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);

    [leftButton  addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width*0.5, 0, self.view.frame.size.width*0.5, 44)];
    //rightView.backgroundColor = [UIColor redColor];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    // 收藏
    mFavButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [mFavButton setImage:[UIImage imageNamed:@"unfav"] forState:UIControlStateNormal];
    [mFavButton setImage:[UIImage imageNamed:@"fav"] forState:UIControlStateSelected];
    [mFavButton addTarget:self action:@selector(favButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    mFavButton.frame = CGRectMake(60, 0, 44, 44);
    [rightView addSubview:mFavButton];
    
    
    mFontButton = [UIButton buttonWithType:UIButtonTypeCustom];
    mFontButton.selected = YES;
    [mFontButton addTarget:self action:@selector(fontButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [mFontButton setTitle:@"Aa" forState:UIControlStateNormal];
    [mFontButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [mFontButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    mFontButton.frame = CGRectMake(114, 0, 44, 44);
    [rightView addSubview: mFontButton];
     
    /*
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    //[shareButton addTarget:self action:@selector(shareBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    shareButton.frame = CGRectMake(mFavButton.frame.size.width + mFontButton.frame.size.width, 0, rightView.frame.size.width/3.0, 44);
    [rightView addSubview:shareButton];
    */
}

- (void)favButtonClick:(id)sender
{
    LibSqlite *db = [LibSqlite shareInstance];
    
    // 已收藏则删除
    if ([self getIsFav]) {
        [db execute:[NSString stringWithFormat:@"DELETE FROM favorite_news WHERE news_id ='%ld'", (long)mNid]];
        mFavButton.selected = NO;
        
        [Util dissmissProcessInView:self.view];
        [Util dismissSuccess:@"删除成功" inView:self.view];
        
        return;
    }
    
    
    if (mData == nil) {
        [Util dissmissProcessInView:self.view];
        [Util dismissSuccess:@"数据正在加载..." inView:self.view];
    }
    
    
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO favorite_news (type, news_id, news_title, news_image_url, news_created) VALUES ('%@', '%li', '%@', '%@', '%@')", @"news", (long)mNid, mData.title, @"", mData.date];
    
    [db execute:sql];
    
    mFavButton.selected = YES;
    
    [Util dissmissProcessInView:self.view];
    [Util dismissSuccess:@"收藏成功" inView:self.view];
}

- (void)fontButtonClick:(id)sender
{
    mFontButton.selected = !mFontButton.isSelected;
    //NSLog(@"%hhd", mFontButton.isSelected);
    //NSLog(@"%hhd", mFontButton.selected);
    if (mFontButton.selected) {
        [mMenu disMiss];
    } else {
        [mMenu show];
    }

}

- (BOOL) getIsFav
{
    
    LibSqlite *db = [LibSqlite shareInstance];
    
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM favorite_news WHERE news_id ='%ld'", (long)mNid];
    
    //NSLog(@"%i", [db getCount:sql]);
    
    if ([db getCount:sql] > 0) {
        
        return YES;
    }
    
    return NO;
}




-(void)backButtonClicked:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


@end
